﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using System.Globalization;

namespace CustomControlLib.TextBoxs
{
    public class WatermarkAdorner:Adorner
    {
        private readonly TextBlock _watermarkTextBlock;

        public WatermarkAdorner(UIElement adornedElement, string watermarkText)
            : base(adornedElement)
        {
            _watermarkTextBlock = new TextBlock
            {
                Text = watermarkText,
                Foreground = new SolidColorBrush(Colors.Gray),
                FontSize = 12,
                VerticalAlignment = VerticalAlignment.Center,
                HorizontalAlignment = HorizontalAlignment.Left,
                Margin = new Thickness(3, 0, 0, 0),
                IsHitTestVisible = false // Ensure the watermark text doesn't interfere with input
            };
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);

            // 获取控件的实际大小
            double renderWidth = this.ActualWidth;
            double renderHeight = this.ActualHeight;

            string text = _watermarkTextBlock.Text;
            Typeface typeface = new Typeface(
                _watermarkTextBlock.FontFamily,
                _watermarkTextBlock.FontStyle,
                _watermarkTextBlock.FontWeight,
                _watermarkTextBlock.FontStretch
            );

            FormattedText formattedText = new FormattedText(
                text,
                CultureInfo.CurrentCulture,
                _watermarkTextBlock.FlowDirection,
                new Typeface(_watermarkTextBlock.FontFamily, _watermarkTextBlock.FontStyle, _watermarkTextBlock.FontWeight, _watermarkTextBlock.FontStretch),
                _watermarkTextBlock.FontSize,
                _watermarkTextBlock.Foreground
            );

            // 计算文本的位置，使其水平居中并垂直居中（考虑文本的高度）
            Point textPosition = new Point(
                (renderWidth - formattedText.Width) / 2,
                (renderHeight - formattedText.Height) / 2
            );

            // 绘制文本
            drawingContext.DrawText(formattedText, textPosition);
        }
    }
}
